# coding=utf8
import time
import requests
import re
import json
import pandas as pd
import numpy as np
import math

appkey = "fc254b20e2ebec432cb90276a0af37ea"

# 先将经纬度转换成六位或五位精度，因为精度过大导致去重困难。
# 除爱彼迎之外都是百度木星座标，需要统一转换成gcj02火星座标
# 有两个数据库是没有采集经纬度信息的： 小猪需要用；api将经纬度补全
xiaozhu = pd.read_pickle('/home/mm/Documents/bnb_data_wrangler/pig2_details.pkl')

xiaozhu_address = xiaozhu.drop_duplicates('address')['address'].values
with open("/home/mm/Documents/bnb_data_wrangler/xiaozhu_gps.csv", "a") as af:
    af.write("address,longitude,latitude")
    for i in range(237):
        print("start", i)
        list_address = xiaozhu_address[10 * i:10 * (i + 1)] if i < 236 else xiaozhu_address[10 * i:]

        url = "https://restapi.amap.com/v3/geocode/geo?output=json&batch=true&key={}&address={}".format(appkey, "|".join(list_address))
        r = requests.get(url)
        str_dict = r.text
        jsondict = json.loads(str_dict)
        csv_str = ""
        for j in range(len(list_address)):
            coords = jsondict['geocodes'][j]['location']
            csv_str += list_address[j] + "," + coords + "\n"
        af.write(csv_str)
        # longitude, latitude = coords.split(",")

# xiaozhushabi = xiaozhu['address'].apply(lambda k: xiaozhugps[['longitude', 'latitude']].loc[xiaozhugps['address'] == k, axis = 1, result_type = 'broadcast')
